<template>
  <el-dialog
    title="选择商品"
    :visible.sync="visible"
    width="80%"
    :before-close="handleClose"
  >
    <!-- 搜索栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
      <el-form-item label="商品名称" prop="storeName">
        <el-input
          v-model="queryParams.storeName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品分类" prop="cateId">
        <el-cascader
          :options="categoryOption"
          :props="{ checkStrictly: true }"
          v-model="selectedIds"
          @change="handleCascaderChange"
          clearable
          placeholder="请选择分类"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 商品列表 -->
    <el-table
      v-loading="loading"
      :data="productList"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="商品ID" align="center" prop="id" width="80" />
      <el-table-column label="商品图片" align="center" width="100">
        <template v-slot="scope">
          <el-image 
            style="width: 60px; height: 60px"
            :src="scope.row.image"
            :preview-src-list="[scope.row.image]"
            fit="cover">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="storeName" show-overflow-tooltip />
      <el-table-column label="商品分类" align="center">
        <template v-slot="scope">
          {{ getCategoryNames(scope.row.cateId) }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 底部按钮 -->
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleConfirm" :disabled="!selectedProducts.length">
        确 定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import * as ProductApi from '@/api/marketing/product';
import * as CategoryApi from '@/api/store/category';
import json from 'highlight.js/lib/languages/json';

export default {
  name: "ProductSelectDialog",
  data() {
    return {
      visible: false,
      loading: false,
      total: 0,
      productList: [],
      categoryList: [],
      // 分类 ID 和分类名称的映射
      categoryIdMap: {},
      // 存储商品分类下拉框选中的id
      selectedIds: [],
      // 级联选择器所需的层级数据
      categoryOption: [],
      // 多选商品
      selectedProducts: [],
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        storeName: null,
        cateId: null,
        isShow: 1, // 只显示上架的商品
        isRecycle: 0, // 不显示回收站的商品
      },
    };
  },
  methods: {
    // 打开弹窗
    open() {
      this.visible = true;
      this.getCategoryList();
      this.getList();
    },
    
    // 关闭弹窗
    handleClose() {
      this.visible = false;
      this.selectedProducts = [];
      this.resetQuery();
    },
    
    // 获取商品列表
    async getList() {
      try {
        this.loading = true;
        const res = await ProductApi.getProductPage(this.queryParams);
        if (res.code === 0) {
          this.productList = res.data.list;
          this.total = res.data.total;
          
        } else {
          this.$message.error(res.msg || '获取商品列表失败');
        }
      } catch (error) {
        console.error('获取商品列表失败:', error);
        this.$message.error('获取商品列表失败');
      } finally {
        this.loading = false;
      }
    },
    
    // 获取分类列表
    async getCategoryList() {
      try {
        const res = await CategoryApi.getCategoryList({ status: 1 });
        if (res.code === 0) {
          this.categoryList = res.data;
          // 转换数据为级联结构
          this.categoryOption = this.buildCascaderOptions(this.categoryList);
          this.buildCategoryIdMap(this.categoryList);
        } else {
          this.$message.error(res.msg || '获取分类列表失败');
        }
      } catch (error) {
        console.error('获取分类列表失败:', error);
        this.$message.error('获取分类列表失败');
      }
    },
    
    // 构建分类 ID 和分类名称的映射
    buildCategoryIdMap(categoryList) {
      categoryList.forEach((category) => {
        this.categoryIdMap[category.id] = category.name;
      });
    },
    
    // 获取级联选择器选中的值
    handleCascaderChange(ids) {
      // 仅当选中最后一级时有效（根据业务需求判断）
      const finalId = ids[ids.length - 1];
      if (finalId) {
        this.queryParams.cateId = finalId;
      } else {
        this.queryParams.cateId = null;
      }
    },
    
    /**
     * 构建级联选择器所需的层级结构
     */
    buildCascaderOptions(list) {
      // 1. 筛选顶级分类（pid=0）
      const rootCategories = list.filter((category) => category.pid === 0);
      // 2. 递归构建子分类
      const buildChildren = (parentId, level = 1) => {
        // 获取当前层级的子分类
        const children = list
          .filter((category) => category.pid === parentId)
          .map((category) => {
            // 构建基础结构
            const option = {
              value: category.id,
              label: category.name,
            };

            // 只在第一级和第二级构建子分类
            // 对于第三级，不构建更深的层级
            if (level < 3) {
              // 递归查找子分类
              const childOptions = buildChildren(category.id, level + 1);
              // 只有当子分类存在时才添加children属性
              if (childOptions && childOptions.length > 0) {
                option.children = childOptions;
              }
            }
            return option;
          });
        return children;
      };
      // 3. 组装顶级分类及其子分类
      return rootCategories.map((category) => {
        const option = {
          value: category.id,
          label: category.name,
        };
        // 构建第一级的子分类
        const children = buildChildren(category.id, 1);
        // 只有当子分类存在时才添加children属性
        if (children && children.length > 0) {
          option.children = children;
        }
        return option;
      });
    },
    
    // 搜索
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    
    // 重置搜索
    resetQuery() {
      // 清空商品分类下拉框中的数据
      this.selectedIds = [];
      // 清除分类id
      this.queryParams.cateId = null;
      // 清除搜索栏数据
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },
    
    // 多选商品变化
    handleSelectionChange(selection) {
      this.selectedProducts = selection;
    },

    // 确认选择
    handleConfirm() {
      if (!this.selectedProducts.length) {
        this.$message.warning('请至少选择一个商品');
        return;
      }
      
      // 触发父组件的选择事件，将所有选中的商品包装成数组
      this.$emit('confirm', this.selectedProducts);
      this.handleClose();
    },

    // 获取行类名
    // 移除 handleRowClick、selectedProduct、currentRowIndex 相关逻辑

    // 根据分类ID获取分类名称
    getCategoryNames(cateIdStr) {
      if (!cateIdStr) return "";
      return cateIdStr
        .split(",")
        .map((id) => this.categoryIdMap[id])
        .join(" 、 ");
    }
  }
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

.el-table .current-row {
  background-color: #f0f9ff !important;
}

.el-table .current-row td {
  background-color: #f0f9ff !important;
}
</style> 